<?php
declare(strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use app\model\Admin;
use app\model\PlatformOperationLog;
use think\facade\{Db, Cache, Config, Log};
use think\Request;
use Firebase\JWT\JWT;

class AuthController extends BaseController
{
    /**
     * 管理员登录
     */
    public function login(Request $request)
    {
        try {
            // 添加调试日志
            Log::debug('Login request params: ' . json_encode($request->post()));
            
            $params = $this->request->post();
            $validate = $this->validate($params, [
                'username' => 'require',
                'password' => 'require'
            ]);
            
            if ($validate !== true) {
                return $this->error($validate);
            }
            
            $admin = Admin::where('username', $params['username'])->find();
            if (!$admin) {
                return $this->error('用户不存在');
            }
            
            if (!password_verify($params['password'], $admin->password)) {
                return $this->error('密码错误');
            }
            
            if ($admin->status != 1) {
                return $this->error('账号已被禁用');
            }

            // 生成JWT token
            $token = $this->generateToken($admin->id);
            
            // 添加调试日志
            Log::debug('Generated token: ' . $token);
            
            // 记录登录日志
            $this->recordLoginLog($admin->id);
            
            return json([
                'code' => 0,
                'msg' => '登录成功',
                'data' => [
                    'token' => $token,
                    'admin' => [
                        'id' => $admin->id,
                        'username' => $admin->username,
                        'role_id' => $admin->role_id,
                        'role_name' => $admin->role->role_name ?? '',
                        'create_time' => $admin->create_time
                    ]
                ]
            ]);
            
        } catch (\Exception $e) {
            Log::error('Login error: ' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }

    /**
     * 生成JWT token
     */
    protected function generateToken($adminId)
    {
        $key = Config::get('jwt.key');
        $expire = Config::get('jwt.expire', 7200);

        $payload = [
            'iss' => 'wasass',  // 签发者
            'aud' => 'admin',   // 接收者
            'iat' => time(),    // 签发时间
            'exp' => time() + $expire,  // 过期时间
            'id' => $adminId,   // 管理员ID
            'type' => 'admin'   // 用户类型
        ];

        return JWT::encode($payload, $key, 'HS256');
    }

    /**
     * 记录登录日志
     */
    protected function recordLoginLog($adminId)
    {
        PlatformOperationLog::create([
            'admin_id' => $adminId,
            'operation_type' => '1', // 操作类型为登录
            'operation_content' => sprintf(
                '管理员(ID:%d)登录系统,登录IP:%s,登录时间:%s',
                $adminId,
                request()->ip(),
                date('Y-m-d H:i:s')
            ),
            'create_time' => date('Y-m-d H:i:s')
        ]);
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $token = $this->request->header('X-Token');
        if ($token) {
            Cache::delete('admin_token_' . $token);
        }
        return json(['code' => 0, 'msg' => '退出成功']);
    }
    
    /**
     * 获取管理员信息
     */
    public function info()
    {
        $adminId = $this->request->adminId;
        $admin = Admin::find($adminId);
        
        if (!$admin) {
            return $this->error('用户不存在');
        }
        
        return json([
            'code' => 0,
            'data' => [
                'id' => $admin->id,
                'username' => $admin->username,
                'role_id' => $admin->role_id,
                'role_name' => $admin->role->role_name ?? '',
                'create_time' => $admin->create_time
            ]
        ]);
    }
} 